﻿using AutoMapper;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Repository;
using DFGK_WMS.WebAPI.Controllers.Result;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NetTaste;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SqlSugar;
using System.Collections.Generic;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Xml.Linq;

namespace DFGK_WMS.WebAPI.Controllers.基础数据
{
    /// <summary>
    /// 站台
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class StationController : ControllerBase
    {
        private readonly ILogRepository logRepository;
        public StationController(ITStationRepository staService,ITMaterialKeyRepository tMaterialKeyRepository, ITStationDataRepository tStationDataRepository, ILogRepository logRepository)
        {
            StaService = staService;
            TMaterialKeyRepository = tMaterialKeyRepository;
            TStationDataRepository = tStationDataRepository;
            this.logRepository = logRepository;
        }

        public ITStationRepository StaService { get; }
        public ITMaterialKeyRepository TMaterialKeyRepository { get; }
        public ITStationDataRepository TStationDataRepository { get; }

        /// <summary>
        /// 添加站台信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddStation(StationDto obj)
        {
            if (string.IsNullOrEmpty(obj.Code))
            {
                return Ok(BaseResult.Result("400", "编码不能为空！"));
            }
            ApiResult apiresult = new ApiResult();
            bool IsOK = StaService.AddStation(obj);
            if (IsOK)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 4;
                logg.ModuleName = "基础数据";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = uid;
                logg.Description = uname + "创建了站台" + obj.Name;
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                apiresult.code = "200";
                apiresult.message = "添加成功!";
                apiresult.data = true;
                return Ok(apiresult);
            }
            apiresult.code = "500";
            apiresult.message = "添加失败!";
            apiresult.data = true;
            return Ok(apiresult);
        }
        /// <summary>
        /// 显示站台信息
        /// </summary>
        /// <param name="ccode"></param>
        /// <param name="cname"></param>
        /// <param name="kid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetStationList(string? cname = "", int kid = 0, int pageIndex = 1, int pageSize = 3)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            ApiResult apiresult = new ApiResult();
            int totalCount;
            var list = StaService.GetStationList(cname, kid, pageIndex, pageSize, out totalCount);
            if (list != null)
            {
                apiresult.code = "200";
                apiresult.message = "获取成功!";
                apiresult.data = list;
                apiresult.count = totalCount;
                return Ok(apiresult);
            }
            apiresult.code = "500";
            apiresult.message = "获取失败!";
            apiresult.data = true;
            return Ok(apiresult);
        }
        /// <summary>
        /// 删除站台信息
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DelStation(int uid)
        {
            if (uid <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            ApiResult apiresult = new ApiResult();
            bool IsOK = StaService.DelStation(uid);
            if (IsOK)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int rid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 5;
                logg.ModuleName = "基础数据";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = rid;
                logg.Description = uname + "删除了站台";
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                apiresult.code = "200";
                apiresult.message = "删除成功!";
                apiresult.data = true;
                return Ok(apiresult);
            }
            apiresult.code = "500";
            apiresult.message = "删除失败!";
            apiresult.data = true;
            return Ok(apiresult);
        }
        /// <summary>
        /// 修改站台信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult UpdateStation(StationDto obj)
        {
            if (obj.Id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            if (string.IsNullOrEmpty(obj.Code))
            {
                return Ok(BaseResult.Result("400", "必填项不能为空！"));
            }
            var res = StaService.UpdateStation(obj);
            ApiResult apiresult = new ApiResult();
            if (res)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 6;
                logg.ModuleName = "基础数据";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = uid;
                logg.Description = uname + "修改了站台" + obj.Name;
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                apiresult.code = "200";
                apiresult.message = "修改成功!";
                apiresult.data = true;
                return Ok(apiresult);
            }
            apiresult.code = "500";
            apiresult.message = "修改失败!";
            apiresult.data = true;
            return Ok(apiresult);
        }
        /// <summary>
        /// 根据id获取站台信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetStationById(int id)
        {
            if (id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var res = StaService.GetStationById(id);
            ApiResult apiresult = new ApiResult();
            if (res != null)
            {
                apiresult.code = "200";
                apiresult.message = "获取成功!";
                apiresult.data = res;
                return Ok(apiresult);
            }
            apiresult.code = "500";
            apiresult.message = "获取失败!";
            apiresult.data = true;
            return Ok(apiresult);
        }
        /// <summary>
        /// 获取库房(仓库)信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTwarehouseList()
        {
            var res = StaService.GetTwarehouseList();
            ApiResult apiresult = new ApiResult();
            if (res != null)
            {
                apiresult.code = "200";
                apiresult.message = "获取成功!";
                apiresult.data = res;
                return Ok(apiresult);
            }
            apiresult.code = "500";
            apiresult.message = "获取失败!";
            apiresult.data = true;
            return Ok(apiresult);
        }
        /// <summary>
        /// 根据物料名称查询物料信息
        /// </summary>
        /// <param name="wname"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTmaterialList(string? wname = "", int pageIndex = 1, int pageSize = 3)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            ApiResult apiresult = new ApiResult();
            int totalCount;
            var list = StaService.GetTmaterialList(wname, pageIndex, pageSize, out totalCount);
            if (list != null)
            {
                apiresult.code = "200";
                apiresult.message = "获取成功!";
                apiresult.data = list;
                apiresult.count = totalCount;
                return Ok(apiresult);
            }
            apiresult.code = "500";
            apiresult.message = "获取失败!";
            apiresult.data = true;
            return Ok(apiresult);
        }
        /// <summary>
        /// 获取物料信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTmaterList()
        {
            var res = StaService.GetTmaterList();
            ApiResult apiresult = new ApiResult();
            if (res != null)
            {
                apiresult.code = "200";
                apiresult.message = "获取成功!";
                apiresult.data = res;
                return Ok(apiresult);
            }
            apiresult.code = "500";
            apiresult.message = "获取失败!";
            apiresult.data = true;
            return Ok(apiresult);
        }
        /// <summary>
        /// 添加站点数据
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddTmater(MaterDto obj)
        {
            ApiResult apiresult = new ApiResult();
            bool IsOK = StaService.AddTmater(obj);
            if (IsOK)
            {
                apiresult.code = "200";
                apiresult.message = "添加成功!";
                apiresult.data = true;
                return Ok(apiresult);
            }
            apiresult.code = "500";
            apiresult.message = "添加失败!";
            apiresult.data = true;
            return Ok(apiresult);
        }
        /// <summary>
        /// 货品明细
        /// </summary>
        /// <param name="zname"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMaterList(string? zname = "", int pageIndex = 1, int pageSize = 3)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            ApiResult apiresult = new ApiResult();
            int totalCount;
            var list = StaService.GetMaterList(zname, pageIndex, pageSize, out totalCount);
            if (list != null)
            {
                apiresult.code = "200";
                apiresult.message = "获取成功!";
                apiresult.data = list;
                apiresult.count = totalCount;
                return Ok(apiresult);
            }
            apiresult.code = "500";
            apiresult.message = "获取失败!";
            apiresult.data = true;
            return Ok(apiresult);
        }


        /// <summary>
        /// 获取站台名称
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetStackStationSelectData()
        {
            var stationlist = StaService.GetStationList(s=>s.StationType== (int)EmStationType.Unstack && s.FunctionType==(int)EmStationFunctionType.InOut);
            if (stationlist == null || stationlist.Count == 0)
            {
                return Ok(BaseResult.Result(null, "", "500"));
            }
            return Ok(BaseResult.Result(stationlist.Select(t=>new
            {
                Id = t.Id,
                Name = t.Name,
                Code = t.Code
            }),"","200"));
        }

        /// <summary>
        /// 站台货品明细的添加修改
        /// </summary>
        /// <param name="stationDatum"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SubmitStationDataForm(TStationDatum stationDatum)
        {
            TStation station = this.StaService.GetStationList(s=>s.Id== stationDatum.StationId).FirstOrDefault();
            if (station != null)
            {
                stationDatum.StationCode = station.Code;
            }
            if (!string.IsNullOrEmpty(stationDatum.BatchNo) && stationDatum.MaterialId > 0)
            {
                TMaterialKey materialKey = TMaterialKeyRepository.GetMaterialKeyList(m=>m.MaterialId==stationDatum.MaterialId && m.BatchNo == stationDatum.BatchNo).FirstOrDefault();
                if (materialKey != null)
                {
                    stationDatum.MaterialKeyId = materialKey.Id;
                }
            }
            bool result = false;
            if (stationDatum.Id > 0)
            {
                result = TStationDataRepository.UpdateTStationDatum(stationDatum);
            }
            else
            {
                result = TStationDataRepository.AddTStationDatum(stationDatum);
            }
            if (result)
            {
                return Ok(BaseResult.Result(null, "保存成功！", "200"));
            }
            return Ok(BaseResult.Result(null, "保存失败！", "500"));
        }

        /// <summary>
        /// 删除站台货品明细
        /// </summary>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DeleteStationDataForm(int id)
        {
            if(id<=0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var isOk = TStationDataRepository.DelTStationDatum(id);
            if (isOk)
            {
                return Ok(BaseResult.Result(null, "删除成功！", "200"));
            }
            return Ok(BaseResult.Result(null, "删除失败！", "500"));
        }

        MemoryStream ProcessExcelData()
        {
            //模块从表中读取的数据
            List<MaterDto> list = new List<MaterDto>();
            list = StaService.GetExcel();
            // 已经读取出了正确的数据后
            //创建Excel对象把数据赋值到对象中
            IWorkbook workbook = new XSSFWorkbook(); // Excel对象
            ISheet sheet1 = workbook.CreateSheet("货品明细");  // 创建Excel中的表对象
            //表头
            IRow row0 = sheet1.CreateRow(0);  // 在sheet1表格中创建第0行
            row0.CreateCell(0).SetCellValue("序号"); // 在sheet1表格中第0行创建第0列，并且在给这个单元格赋值
            row0.CreateCell(1).SetCellValue("表条码");
            row0.CreateCell(2).SetCellValue("箱条码");
            row0.CreateCell(3).SetCellValue("批次号");
            row0.CreateCell(4).SetCellValue("站台编码");
            row0.CreateCell(5).SetCellValue("状态");
            row0.CreateCell(6).SetCellValue("创建时间");
            var rowIndex = 1;
            foreach (var item in list)
            {
                var stock = "";
                if (item.IsStocktake == true)
                {
                    stock = "是";
                }
                if (item.IsStocktake == false)
                {
                    stock = "否";
                }
                IRow row = sheet1.CreateRow(rowIndex);
                row.CreateCell(0).SetCellValue(item.Id);
                row.CreateCell(1).SetCellValue(item.Barcode);
                row.CreateCell(2).SetCellValue(item.PackageBarcode);
                row.CreateCell(3).SetCellValue(item.BatchNo);
                row.CreateCell(4).SetCellValue(item.StationCode);
                row.CreateCell(5).SetCellValue(stock);
                row.CreateCell(6).SetCellValue(item.CreateDate.ToString());
                rowIndex++;
            }
            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);

            return ms;
        }
        //MemoryStream ProcessExcelData()
        //{
        //    // 模块从表中读取的数据
        //    List<MaterDto> list = new List<MaterDto>();
        //    list = StaService.GetExcel();

        //    // 已经读取出了正确的数据后
        //    // 创建Excel对象把数据赋值到对象中
        //    IWorkbook workbook = new XSSFWorkbook(); // Excel对象
        //    ISheet sheet1 = workbook.CreateSheet("货品明细");  // 创建Excel中的表对象

        //    // 设置表头
        //    IRow row0 = sheet1.CreateRow(0);  // 在sheet1表格中创建第0行
        //    row0.CreateCell(0).SetCellValue("序号");
        //    row0.CreateCell(1).SetCellValue("表条码");
        //    row0.CreateCell(2).SetCellValue("箱条码");
        //    row0.CreateCell(3).SetCellValue("批次号");
        //    row0.CreateCell(4).SetCellValue("站台编码");
        //    row0.CreateCell(5).SetCellValue("状态");
        //    row0.CreateCell(6).SetCellValue("创建时间");

        //    var rowIndex = 1;
        //    foreach (var item in list)
        //    {
        //        var stock = "";
        //        if (item.IsStocktake == true)
        //        {
        //            stock = "是";
        //        }
        //        if (item.IsStocktake == false)
        //        {
        //            stock = "否";
        //        }
        //        IRow row = sheet1.CreateRow(rowIndex);
        //        row.CreateCell(0).SetCellValue(item.Id);
        //        row.CreateCell(1).SetCellValue(item.Barcode);
        //        row.CreateCell(2).SetCellValue(item.PackageBarcode);
        //        row.CreateCell(3).SetCellValue(item.BatchNo);
        //        row.CreateCell(4).SetCellValue(item.StationCode);
        //        row.CreateCell(5).SetCellValue(stock);
        //        row.CreateCell(6).SetCellValue(item.CreateDate.ToString());
        //        rowIndex++;
        //    }

        //    // 创建一个UTF-8编码的MemoryStream
        //    var utf8Encoding = new System.Text.UTF8Encoding();
        //    MemoryStream ms = new MemoryStream(utf8Encoding.GetBytes(""));

        //    // 使用UTF-8编码写入到MemoryStream
        //    workbook.Write(ms);

        //    return ms;
        //}
        /// <summary>
        /// 下载货品明细
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public FileContentResult DownStation()
        {
            MemoryStream ms = ProcessExcelData();
            byte[] fileBytes = ms.ToArray();
            return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, "货品明细.xlsx"); //关键语句
        }
        /// <summary>
        /// 获取枚举站台类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetEmStationType()
        {
            var list = BaseEnum.GetCodeRulesList<EmStationType>();

            return Ok(list);
        }

        /// <summary>
        /// 获取站台功能类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetEmStationFunctionType()
        {
            var list = BaseEnum.GetCodeRulesList<EmStationFunctionType>();

            return Ok(list);
        }
    }
}
